package org.ipmsg.core.net;

import org.ipmsg.core.Address;
import org.ipmsg.core.Message;
import org.ipmsg.core.event.DatagramEvent;
import org.ipmsg.core.event.DatagramReceiveListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Enumeration;
import java.util.Hashtable;

public class DatagramReceive extends Thread {

    private DatagramSocket udpSocket;
    private Hashtable listeners;
    private int maxBuffer;

    public DatagramReceive(DatagramSocket argds, int maxBuffer) {
        udpSocket = argds;
        this.maxBuffer = maxBuffer;
        listeners = new Hashtable();
    }

    public void addIPMsgRecvListener(DatagramReceiveListener listener) {
        listeners.put(listener, listener);
    }

    public void removeIPMsgRecvListener(DatagramReceiveListener listener) {
        listeners.remove(listener);
    }

    @Override
    public void run() {
        byte tmpbuf[] = new byte[maxBuffer];
        do {
            DatagramPacket packet = new DatagramPacket(tmpbuf, tmpbuf.length);
            try {
                udpSocket.receive(packet);
            } catch (IOException ex) {
                ex.printStackTrace();
                continue;
            }
            byte buf[] = new byte[packet.getLength()];
            System.arraycopy(tmpbuf, 0, buf, 0, buf.length);
            Message tmppack = new Message(buf);
            Address tmpaddr = new Address(packet.getPort(), packet.getAddress());
            DatagramEvent tmpevent = new DatagramEvent(this, tmppack, tmpaddr);
            synchronized (this) {
                DatagramReceiveListener listener;
                for (Enumeration em = listeners.elements(); em.hasMoreElements(); listener.receiveEvent(tmpevent)) {
                    listener = (DatagramReceiveListener) em.nextElement();
                }

            }
        } while (true);
    }
}
